// const { formatTime } = require("../../../utils/util");
// packageE/groupCode/groupCodeEdit/groupCodeEdit.js
const skinBehavior = require('../../../utils/themeSkin/skinBehavior');
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  behaviors: [skinBehavior],
  data: {
    swlist: [],
    code_url: [],
    code_data_img: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.id) {
      this.setData({
        id: options.id,
      });
    }
    this.getData();
  },
  name(e) {
    let val = e.detail.value;
    this.setData({
      "info.code_name": val,
    });
  },
  guide(e) {
    let val = e.detail.value;
    this.setData({
      "info.code_guide": val,
    });
  },
  service_guide(e) {
    let val = e.detail.value;
    this.setData({
      "info.customer_service_guide": val,
    });
  },
  change(e) {
    let val = e.detail;
    this.setData({
      "info.explain": val,
      "info.explain_content": "",
    });
  },
  change1(e) {
    let val = e.detail;
    this.setData({
      "info.recommend": val,
    });
  },
  // 选择图片
  onRead() {
    let that = this;
    let urlStr = app.getNetAddresss("upload.uploadPic");
    wx.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
      success(res) {
        const tempFilePaths = res.tempFilePaths;

        wx.compressImage({
          src: tempFilePaths[0], // 图片路径
          quality: 60, // 压缩质量
          success(e) {
            wx.showLoading({
              title: "上传中",
            });
            let photourl = e.tempFilePath;
            wx.uploadFile({
              url: urlStr,
              filePath: photourl,
              name: "file",
              success(resdata) {
                wx.hideLoading({
                  success: (res) => {},
                });
                var res = JSON.parse(resdata.data);
                if (res.result == 1) {
                  that.setData({
                    imageUrl: res.data.img_url,
                    "info.customer_service": res.data.img,
                  });
                } else {
                  wx.showToast({
                    icon: "none",
                    title: res.msg,
                    duration: 1500,
                  });
                }
              },
            });
          },
          fail(e) {},
          complete(e) {},
        });
      },
    });
  },
  // 群二维码  多图上传
  onRead_2() {
    let that = this;
    // let urlStr = app.getNetAddresss("upload.uploadPic");
    let ig = "1";
    wx.chooseImage({
      count: 9,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
      success(res) {
        // var tempFilePaths = res.tempFilePaths
        that.unload(
          {
            tempFilePaths: res.tempFilePaths,
          },
          ig
        );
      },
    });
  },
  //多张上传方法
  unload(data, ig) {
    console.log(ig);
    wx.showLoading({
      title: "上传中",
    });
    let urlStr = app.getNetAddresss("upload.uploadPic");
    var that = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
    wx.uploadFile({
      url: urlStr,
      filePath: data.tempFilePaths[i],
      name: "file",
      formData: null,
      success(resdata) {
        wx.hideLoading({
          success: (res) => {},
        });
        var res = JSON.parse(resdata.data);
        if (ig == "1") {
          // that.data.code_data_img.push({ code_url: res.data.img_url });
          that.data.code_data.push({ code_url: res.data.img_url });
          that.setData({
            code_data: that.data.code_data,
          });
        } else if (ig == 2) {
          that.data.code_data.push({ code_url: res.data.img_url });
          that.setData({
            code_data: that.data.code_data,
          });
        }
      },
      fail(e) {
        wx.hideLoading({
          success: (res) => {},
        });
        fail++;
      },
      complete(e) {
        wx.hideLoading({
          success: (res) => {},
        });
        i++;
        if (i == data.tempFilePaths.length) {
          //当图片传完时，停止调用
          console.log("执行完毕");
          console.log("成功：" + success + " 失败：" + fail);
        } else {
          //若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.unload(data, ig); //递归，回调自己
        }
      },
    });
  },
  delImg(e) {
    let ind = e.currentTarget.dataset.ind;
    let list = this.data.code_data;
    // let lis = this.data.code_data_img;
    console.log(list);
    // lis.splice(ind, 1);
    list.splice(ind, 1);
    console.log(list, "截取后");
    this.setData({
      code_data: list,
      // code_data_img: lis,
    });
  },
  // 扫码上限人数
  upperLimit(e) {
    let val = e.detail.value;
    let ind = e.currentTarget.dataset.ind;
    let code_data = this.data.code_data;
    code_data[ind].upper_limit = val;
  },
  explaincon(e) {
    let val = e.detail.value;
    this.setData({
      "info.explain_content": val,
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getset();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  save() {
    let info = this.data.info;
    let list = this.data.code_data;
    if (list.length === 0) {
      wx.showToast({
        title: "请上传群二维码",
        icon: "none",
        duration: 1000,
      });
      return;
    }
    // 检查有没有填写扫码上限人数
    for (let i = 0; i < list.length; i++) {
      if ("upper_limit" in list[i] == false) {
        wx.showToast({
          title: "请输入扫码上限人数",
          icon: "none",
          duration: 1000,
        });
      }
    }
    let json = {
      id: Number(this.data.id),
      code_name: info.code_name,
      code_guide: info.code_guide,
      explain: info.explain ? "1" : "0",
      customer_service: info.customer_service,
      customer_service_guide: info.customer_service_guide,
      code_data: JSON.stringify(this.data.code_data),
    };
    if (info.explain) {
      json.explain_content = info.explain_content;
      if (app._isTextEmpty(info.explain_content)) {
        wx.showToast({
          title: "请输入说明内容",
        });
        return;
      }
    }
    if (info.recommend) {
      json.recommend = info.recommend ? "1" : "0";
    }
    this.saveSubmit(json);
  },
  getData() {
    var that = this;
    let urlStr = app.getNetAddresss("plugin.group-code.api.group-code.detail");
    app._postNetWork({
      url: urlStr,
      data: {
        id: that.data.id,
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          let codeData = res.data.data;
          let code_data = [];
          for (let i = 0; i < res.data.data.has_many_code.length; i++) {
            code_data.push({
              code_url: res.data.data.has_many_code[i].code_url_img,
              upper_limit: res.data.data.has_many_code[i].upper_limit,
              id: res.data.data.has_many_code[i].id,
            });
          }
          console.log(code_data);
          that.setData({
            info: res.data.data,
            code_data: code_data,
            code_data_img:code_data,
            'info.customer_service':res.data.data.customer_service_img,
            'info.explain_content' :codeData.explain_content?.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;"'),
            'info.explain':codeData.explain == 1?true:false,
            'info.recommend':codeData.recommend == 1?true:false
          });
          
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
          });
        }
      },
    });
  },
  getset() {
    let urlStr = app.getNetAddresss("plugin.group-code.api.set.index");
    app._postNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.setData({
            is_open: res.data.set.is_open,
            auth_recommend: res.data.set.auth_recommend,
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
          });
        }
      },
    });
  },
  saveSubmit(json) {
    let urlStr = app.getNetAddresss("plugin.group-code.api.group-code.update");
    app._postNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          console.log(res);
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1000,
            success: function (e) {
              setTimeout(() => {
                wx.navigateBack({
                  delta: 1,
                });
              }, 1500);
            },
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
          });
          console.log(res.msg);
        }
      },
    });
  },
});
